package client;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.donovanhatch.androidClient.R;

import android.app.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;

/**
 * @author Donovan
 * 
 * Main activity for android application. Initializes user interface
 * Checks location in comparison to baseLocation, and starts the client.
 *
 */

@SuppressWarnings("unused")
public class AndroidLocationClientActivity extends Activity {

	private EditText mInput = null;
    private EditText mOutput = null;
    private ToggleButton mProfile = null;
    private Client clientInstance = null;
    private String ipAddress = null;
    private int port = 0;
    private WifiManager wifi = null;
    private WifiInfo wifiInfo = null;
    private boolean newWifiResults = false;
    private List<ScanResult> wifiScanResults = null;
    private Location cellLoc = null;
    private Location baseLocation = null;
    private Connection ctn = null;
    private BroadcastReceiver br = null;
	
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    	SharedPreferences settings = getSharedPreferences("com.donovanhatch.com.androidClient",MODE_PRIVATE);
    	
        ipAddress = settings.getString("ipAddress", "0.0.0.0");
        port = settings.getInt("port", 0);
        baseLocation = new Location(settings.getString("baseLocation", null));
        
        mInput = (EditText)findViewById(R.id.input);
        mOutput = (EditText)findViewById(R.id.output);
        mProfile = (ToggleButton)findViewById(R.id.profileToggle);
                   	    	
    	if(ipAddress != "0.0.0.0" && port != 0){
        	Client.setIpAddress(ipAddress);
        	Client.setPort(port);
        	clientInstance = Client.getInstance();
        } else {
        	Toast toast = Toast.makeText(getApplicationContext(), "Go to settings and enter server details now!", Toast.LENGTH_LONG);
    		toast.show();
        }
    	
    	wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        wifiInfo = wifi.getConnectionInfo();
         
        br = new BroadcastReceiver(){
			public void onReceive(Context context, Intent intent) {
				wifiScanResults = wifi.getScanResults();
				newWifiResults = true;
			}
		};
        		
		registerReceiver(br, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); 
               
        wifi.startScan();
    	
    	ctn = new Connection();
    	ctn.start();    	
    }
            
    /** 
     * displays the popup menu on menu button push
     */
    public boolean onCreateOptionsMenu(Menu menu){
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }
    
    /**
     * determines which menu item was pushed
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.server:
        	 Intent intent = new Intent(this, ServerEditor.class);
             this.startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }  
    
 /**
 * @author Donovan
 * 
 * Thread that runs constantly to check connection to wifi.
 * If wifi is enabled and client is connected to the server, thread sleeps for 1 minute
 * If wifi is enabled and disconnected from server, trys to connect to server.
 * If wifi is disabled, currentDistance is checked with baseLocation
 * to see if we are within 3 miles. If we are within 3 miles, wifi is turned on 
 *
 */
public class Connection extends Thread {
    	public void run() {
    		while(true){
    			if(wifi.isWifiEnabled()){
    				if((clientInstance != null) && clientInstance.isConnected()){
    					if(newWifiResults == true){
    	    				wifiInfo = wifi.getConnectionInfo();
    	    				Map<String, Integer> otherNetworks = new HashMap<String,Integer>();
    	    				for(ScanResult sr : wifiScanResults){
    	    					otherNetworks.put(sr.BSSID, sr.level);
    	    				}
    	    				clientInstance.sendWifiObject(wifiInfo, mProfile.isChecked(), otherNetworks, mInput.getText().toString());
    	    				newWifiResults = false;
    	    				wifi.startScan();	
    	    			}	
	    	    		try {
							sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
    				} else {
    					if(clientInstance != null){
    						clientInstance.tryConnect();
    					}
    				}
    	    	} else {
    	    		if(cellLoc != null){
	    	    		if(cellLoc.distanceTo(baseLocation) <= 4828) {  //3 miles -> meters
	    	    			wifi.setWifiEnabled(true);
	                	} 
    	    		}
    	    	}
    		}
    	}
    }
}